from fastapi import APIRouter, Depends, HTTPException, Body,Request
from fastapi.security import OAuth2PasswordBearer  # 新增导入
from ..schemas.user import *  # 确保User也被导入
from app.services.auth import *
from ..db.session import get_db
from sqlalchemy.orm import Session
from app.utils.security import get_current_user, oauth2_scheme  # 确保oauth2_scheme被导入
from app.services.captcha import CaptchaService
from app.utils.security import add_to_blacklist
from datetime import datetime
from loguru import logger

router = APIRouter(prefix="/auth", tags=["认证管理"])

@router.post("/login", summary="普通账号密码登录")
async def login_with_username(
    request: Request,  # 添加Request参数
    request_data= Body(...),
    db: Session = Depends(get_db)
):
    # 1. 验证用户凭证
    user = AuthService.authenticate_user_by_nickname(
        db, 
        request_data["nickname"],  # 使用nickname作为用户名
        request_data["password"]
    )
    if not user:
        raise HTTPException(
            status_code=400,
            detail="用户名或密码错误"
        )
    
    # 2. 创建访问令牌
    access_token = AuthService.create_access_token(
        data={"sub": user.email}  # 令牌中仍然使用email作为sub
    )
    
    # 在返回令牌前更新用户在线状态
    user.online = True
    db.commit()
    
    return {
        "code": 200,
        "data": {
            "access_token": access_token,
            "expires_in": 7200
        }
    }

@router.post("/emailLogin", summary="邮箱验证码登录")
async def login_with_email(
    request_data = Body(...,
        example={
            "email": "user@example.com",
            "captcha": "123456"
        },
        description="""
        登录请求参数:
        - email: 必填，注册时使用的邮箱
        - captcha: 必填，6位数字验证码
        """),
    db: Session = Depends(get_db) 
):
    # 1. 验证验证码
    if not CaptchaService.verify_captcha(request_data["email"], request_data["captcha"]):
        raise HTTPException(status_code=400, detail="验证码错误或已过期")
    
    # 2. 获取用户
    user = UserService.get_user_by_email(db, request_data["email"])
    if not user:
        raise HTTPException(status_code=400, detail="邮箱未注册")
    
    # 3. 创建访问令牌
    access_token = AuthService.create_access_token(
        data={"sub": user.email}
    )
    
    # 更新用户在线状态
    user.online = True
    db.commit()
    
    return {
        "code": 200,
        "data": {
            "access_token": access_token,
            "expires_in": 7200
        }
    }

@router.get("/captcha/login", summary="登录验证码获取")
async def get_login_captcha(email: str):
    """发送验证码到对应邮箱"""
    captcha = CaptchaService.generate_captcha(email)
    logger.debug(f"登录验证码: {captcha}")  # 开发环境直接打印
    return {"message": "验证码已发送"}

@router.get("/captcha/register", summary="注册验证码获取") 
async def get_register_captcha(email: str):
    """发送验证码到对应邮箱"""
    captcha = CaptchaService.generate_captcha(email)
    logger.debug(f"注册验证码: {captcha}")  # 开发环境直接打印
    return {"message": "验证码已发送"}

@router.post("/register", summary="用户名密码注册")
async def register_with_username(
    request_data = Body(...,
      example={
            "email": "user@example.com",
            "password": "yourpassword123",
            "nickname": "张三",
            "sex": 1,
            "captcha": "123456"
        },),  # 改为直接接收整个请求体
    db: Session = Depends(get_db)
):
    """
    用户注册接口
    
    请求参数：
    - email: 必填，用户邮箱（唯一标识）
    - password: 必填，密码（至少8位）
    - nickname: 必填，昵称（2-20字符）
    - sex: 可选，性别
    
    返回示例：
    ```json
    {
        "code": 200,
        "data": {
            "message": "注册成功",
            "user_id": user.userid
        }
    }
    ```
    """
    
    captcha = request_data.get("captcha")
    if not captcha:
        raise HTTPException(status_code=400, detail="验证码不能为空")
    
    # 验证验证码
    if not CaptchaService.verify_captcha(request_data["email"], captcha):
        raise HTTPException(status_code=400, detail="验证码错误或已过期")
    
    # 验证并转换用户数据
    try:
        user_data = UserCreate(**{
            "email": request_data["email"],
            "password": request_data["password"],
            "nickname": request_data["nickname"],
            "sex": request_data.get("sex", 0)
        })
    except Exception as e:
        raise HTTPException(status_code=422, detail=str(e))
    
    
    # 1. 检查邮箱是否已存在
    if UserService.get_user_by_email(db, user_data.email):
        raise HTTPException(status_code=400, detail="邮箱已注册")
    
    # 2. 密码加密
    hashed_password = AuthService.hash_password(user_data.password)
    
    # 3. 创建用户
    user = UserService.create_user(
        db=db,
        email=user_data.email,
        password=hashed_password,
        nickname=user_data.nickname,
        sex=user_data.sex
    )
    
    return {
        "code": 200,
        "data": {
            "message": "注册成功",
            "user_id": user.userid
        }
    }

@router.get("/captcha/register", summary="注册验证码获取")
async def get_register_captcha():
    """发送验证码到对应邮箱"""
    pass

from app.schemas.user import UserOut  # 使用Pydantic模型

@router.get("/userinfo", response_model=UserResponse, summary="获取当前用户信息")
async def get_user_info(
    current_user: UserOut = Depends(get_current_user),  # 通过token解析用户
    db: Session = Depends(get_db)
):
    #打印请求头信息
    """
    获取当前登录用户的详细信息
    返回示例：
    ```json
  {
  "code": 200,
  "data": {
    "email": "user@example.com",
    "nickname": "张三",
    "avatar": "http://example.com/avatar.jpg",
    "sex": 1,
    "online": true,
    "created_at": "2023-01-01T00:00:00",
    "last_at": "2023-01-02T12:00:00"
    }
}
    ```
    """
    return {
        "code": 200,
        "message": "获取用户信息成功",
        "data": current_user.model_dump()
    }

@router.post("/logout", summary="退出登录")
async def logout(
    token: str = Depends(oauth2_scheme),
    current_user: UserOut = Depends(get_current_user),
    db: Session = Depends(get_db)  # 添加db依赖
):
    """
    用户退出登录接口
    1. 将当前令牌加入黑名单
    2. 更新用户在线状态为离线
    """
    # 1. 将令牌加入黑名单
    await add_to_blacklist(token)
    user = db.query(User).filter(User.email == current_user.email).first()
    if user:
        user.online = False
        user.last_at = datetime.now()
        db.add(user)
        db.commit()
        db.refresh(user)
    else:
        raise HTTPException(status_code=404, detail="用户未找到")
    
    return {
        "code": 200,
        "data": {
            "message": "退出登录成功",
            "user_id": current_user.userid
        }
    }